import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/all_widget/head_image.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/bottommenu.dart';
import 'package:wayofdressing/components/message.dart';
import 'package:wayofdressing/dio/MessageDio.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/screens/own_screen.dart';

import '../all_information/user_information.dart';

class ChatScreen extends StatefulWidget {
  static final String id = 'ChatScreen';

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {

  int senderId=0;
  int receiverId=0;
  String receiverName='';
  String senderName='';

  TextEditingController textController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  final FocusNode _contentFocusNode = FocusNode();
  Widget bottomMenu = const SizedBox();
  Widget trailingIcon = Container();
  List<Widget> messages = [];

  bool isOpen = false;
  ImageProvider receiverHeadImage=AssetImage('images/peanut.jpg');


  Future<void> _getMessages() async {
    try {
      SharedPreferences prefs=await SharedPreferences.getInstance();
      senderId=prefs.getInt('id')!;
      senderName=name;
      await _getReceiverIdAndHeadImage();
      Response response1 = await getMessageByUserIdAndReceiverId(
        userId: senderId,
        receiverId: receiverId,
        dio: dio,
      );
      List<dynamic> data1 = response1.data['data'];
      List<Message> fetchedMessages = data1
          .map((msg) => Message(
        id: senderId,
        name: senderName,
        oppositeHeadImage: headImage,
        text: msg['messageText'],
        isOpposite: false,
        sentAt: DateTime.parse(msg['sentAt']), // 解析时间字符串为 DateTime 对象
      ))
          .toList();
      Response response2 = await getMessageByUserIdAndReceiverId(
        userId: receiverId,
        receiverId: senderId,
        dio: dio,
      );
      List<dynamic> data2 = response2.data['data'];
      List<Message> fetchedMessages2 = data2
          .map((msg) => Message(
        id: receiverId,
        name: receiverName,
        oppositeHeadImage: receiverHeadImage,
        text: msg['messageText'],
        isOpposite: true,
        sentAt: DateTime.parse(msg['sentAt']),
      ))
          .toList();
      // 合并并按时间排序
      List<Message> allMessages = [];
      allMessages.addAll(fetchedMessages);
      allMessages.addAll(fetchedMessages2);
      allMessages.sort((a, b) => a.sentAt.compareTo(b.sentAt));

      setState(() {
        messages = allMessages;
      });

      // 滚动到底部
      Future.delayed(const Duration(milliseconds: 200), () {
        _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
      });
    } catch (e) {
      print('Error fetching messages: $e');
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Error'),
            content: Text('Failed to fetch messages.'),
            actions: <Widget>[
              TextButton(
                child: Text('OK'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }
  Future<void> _getReceiverIdAndHeadImage() async {
    final Map<String, dynamic>? args =
    ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;

    setState(() {
      receiverId = args?['receiverId'] ?? 0; // 获取 receiverId
      receiverHeadImage=args?['headImage']??AssetImage('images/peanut.jpg');
      receiverName= args?['receiverName'] ?? '';
    });
  }
  Future<void> _sendMessage() async {
    try {
      String sendText=textController.text;
      textController.clear();
      await sendMessageByUserIdAndReceiverId(
        messageText: sendText,
        senderId: senderId,
        receiverId: receiverId,
        dio: dio, // 假设 _dio 是您的 Dio 实例，需要提前初始化
      );
      print('消息发送成功');
      // 清空输入框或者更新 UI，视情况而定
    } catch (e) {
      print('发送消息失败: $e');
      // 处理发送失败的情况，可以弹出提示或者进行其他操作
    }
  }

  @override
  void initState() {
    super.initState();
    trailingIcon=menuButton();
    _getMessages();
  }
  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
    textController.dispose();
    _contentFocusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 100,
        centerTitle: true,
        title: Text(
          receiverName,
          style: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontSize: kTopTitleFontSize,
          ),
        ),
        leading: Row(
          children: [
            SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
        actions: [
          GestureDetector(
            onTap: (){
              Navigator.pushNamed(context, OwnScreen.id,arguments: {'name':receiverName,'id':receiverId,'headImage':receiverHeadImage});
            },
            child: Icon(
              Icons.keyboard_control_rounded,
              size: kAppBarButtonSize,
              color: Colors.black,
            ),
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              controller: _scrollController,
              itemCount: messages.length,
              itemBuilder: (context, index) {
                return messages[index];
              },
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            height: 70,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 42,
                  height: 42,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(25),
                      border: Border.all(color: Colors.black, width: 4)),
                  child: Icon(
                    Icons.mic_none_rounded,
                    color: Colors.black,
                    size: 35,
                  ),
                ),
                Container(
                  margin: EdgeInsets.symmetric(vertical: 12, horizontal: 10),
                  width: MediaQuery.of(context).size.width - 150,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25.0),
                    color: Colors.black.withOpacity(0.3),
                  ),
                  child: TextField(
                    focusNode: _contentFocusNode,
                    controller: textController,
                    cursorColor: Colors.white,
                    onChanged: (value) {
                      setState(() {
                        if (textController.text != '') {
                          trailingIcon = sendButton();
                        } else {
                          trailingIcon = menuButton();
                        }
                      });
                    },
                    style: const TextStyle(
                      color: Colors.black,
                      fontSize: 18,
                    ),
                    decoration: InputDecoration(
                      contentPadding:
                          EdgeInsets.symmetric(horizontal: 15, vertical: 13),
                      border: InputBorder.none,
                    ),
                  ),
                ),
                trailingIcon,
              ],
            ),
          ),
          bottomMenu,
        ],
      ),
    );
  }

  GestureDetector menuButton() {
    return GestureDetector(
      onTap: () {
        setState(() {
          _contentFocusNode.unfocus();
          if (!isOpen) {
            bottomMenu = BottomMenu(context: context);
            isOpen = true;
          } else {
            bottomMenu = const SizedBox();
            isOpen = false;
          }
        });
      },
      child: const Icon(
        Icons.add_circle_outline_rounded,
        size: 50,
        color: Colors.black,
      ),
    );
  }

  GestureDetector sendButton() {
    return GestureDetector(
      onTap: () async{
        trailingIcon = menuButton();
          await _sendMessage();
          await _getMessages();
        Future.delayed(const Duration(milliseconds: 200), () {
          _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
        });
      },
      child: CircleAvatar(
        backgroundColor: Colors.blueAccent,
        child: const Icon(
          Icons.send_rounded,
          size: 28,
          color: Colors.white,
        ),
      ),
    );
  }
}
